package api

import (
	"github.com/gin-gonic/gin"
	"monthly-test/global"
	"monthly-test/internal/model/dao"
	"monthly-test/internal/model/service"
	"monthly-test/internal/response"
	"net/http"
	"strconv"
)

// 添加好友 可以在已注册添加一个或多个
func AddFriends(c *gin.Context) {
	account := c.PostForm("account")
	//查询账号是否存在 存在添加好友
	byAccount, err := service.CheckUserByAccount(account)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "用户不存在"})
		return
	}
	friend := dao.Friend{
		UserId:   1, //模拟用户
		FriendId: int(byAccount.ID),
		Name:     byAccount.Name,
	}
	err = global.DB.Create(&friend).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "添加失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "添加好友成功"})

}

// 删除好友
func DelFriend(c *gin.Context) {

	friendId, _ := strconv.Atoi(c.Query("friendId"))
	friend := dao.Friend{
		FriendId: friendId,
	}
	err := global.DB.Where("friend_id = ?", friendId).Delete(&friend).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "失败", "error": err})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "好友删除成功"})
}

// 好友列表
func FriendList(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Query("userId"))
	list, err := service.FriendList(userId)
	if err != nil {
		return
	}

	err = global.DB.Where("status = 1").Order("name DESC").Find(&list).Error
	err = global.DB.Where("status = 0").Find(&list).Error

	var slice []response.ListResponse
	for _, friend := range list {
		slice = append(slice, response.ListResponse{
			UserId:   friend.UserId,
			FriendId: friend.FriendId,
			Name:     friend.Name,
		})
	}
	c.JSON(http.StatusOK, gin.H{"data": slice})

}
